#include "plcemu.h"

//todo COMEDI probing
static comedi_t * it;

int enable_bus() /* Enable bus communication */
{
	int uid;
	char filestr[256];
	
//	if(!USE_COMEDI)
//	{
	
	    uid=getuid();		/* get User id */
	    seteuid(0);		/* set User Id to root (0) */
	    if (geteuid()!=0)
	    {
		fprintf(stderr,"FATAL ERROR: UNABLE TO CHANGE TO ROOT\n");
		return -1;
	    }
	    if (iopl(3))		/* request bus WR i/o permission */
	    {
		fprintf(stderr,"FATAL ERROR: UNABLE TO GET I/O PORT PERMISSION\n");
		perror("iopl() ");
		seteuid(uid);
		return -1;
	    }
	    seteuid(uid);		/* reset User Id */
	    outb(0,Base+Wr_offs);//clear outputs port
/*	}
	else
	{
	    memset(filestr,0,256);
	    sprintf(filestr,"/dev/comedi%d",Comedi_file);
	    printf(filestr);
	    if((it = comedi_open(filestr))==NULL)
		return -1;
	}*/
	printf("io card enabled\n");
	return 1;
}

int disable_bus() /* Disable bus communication */
{
	int uid,i,j,n;
	for(i = 0; i< Dq;i++)
	{	//write zeros
	    for(j = 0; j < 8;j++)
	    {//zero n bit out
		n = 8*i+j;
    		dio_write(plc.outputs,n,0);
    	    }
	}
//	if(!USE_COMEDI)
//	{

	    uid=getuid();		/* get User id */
	    setuid(0);		/* set User Id to root (0) */
	    if (getuid()!=0)
	    {
		fprintf(stderr,"Unable to change id to root\nExiting\n");
		return -1;
	    }
	    if (iopl(0))		/* Normal i/o prevelege level */
	    {
		perror("iopl() ");
    		setuid(uid);
		return -1;
	    }
    	    setuid(uid);		/* reset User Id */
/*	}
	else
	    comedi_close(it);*/
}
void dio_read(int n, BYTE* bit)
{//write input n to bit
    unsigned int b;
//    if(!USE_COMEDI)
//    {
	BYTE i;
	i = inb(Base+Rd_offs+n/8);
	b=(i>>n%8)%2;
	*bit=(BYTE)b;
/*    }
    else
    {
	 comedi_dio_read(it,Comedi_subdev_i,n,&b);
	*bit=(BYTE)b;
    }*/
}
void dio_write(BYTE * buf,int n, int bit)
{//write bit to n output
    BYTE q;
    q=buf[n/8];
    q|=bit<<n%8;
//    if(!USE_COMEDI)
	outb(q,Base+Wr_offs+n/8);
//    else
//	comedi_dio_write(it,Comedi_subdev_q,n,bit);
}
void dio_bitfield(BYTE * write_mask, BYTE * bits)
{//simultaneusly write output bits defined my mask and read all inputs
    int i,j,n,in;
    unsigned int w,b;
//    if(!USE_COMEDI)
//    {
	for(i=0;i<Dq;i++)
    	    outb(bits[i] & write_mask[i], Base+Wr_offs+i);
	for(i=0;i<Di;i++)
	    bits[i]=inb(Base+Rd_offs+i);
//    }
/*    else
    {
	w=(unsigned int)(*write_mask);
	b=(unsigned int)(*bits);
	comedi_dio_bitfield(it,Comedi_subdev_i,w,&b);
    }*/
}
